import os

from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.mail import send_mail
from django.db import models
from db import BaseModel
from django.template.loader import get_template

User = get_user_model()


def image_path(instance, filename):
    """
    :param instance: Profile对象
    :param filename: 文件名
    :return: 图片文件上传的路径
    """
    return os.path.join('avatar', f'user_{instance.user.pk}', filename)


class Profile(models.Model):
    """个人主页模型"""
    user = models.OneToOneField(User, verbose_name='用户', on_delete=models.CASCADE)
    avatar = models.ImageField('个人头像', default='default.jpg', upload_to=image_path)

    class Meta:
        verbose_name = verbose_name_plural = '个人中心'

    def __str__(self):
        return f'{self.user!s}主页'


class Friendship(BaseModel):
    """添加好友模型"""

    # 主动添加好友方
    from_friend = models.ForeignKey(
        User,
        verbose_name='用户',
        related_name='from_friendship_set',
        on_delete=models.CASCADE
    )

    # 被加为好友方
    to_friend = models.ForeignKey(
        User,
        verbose_name='朋友',
        related_name='to_friendship_set',
        on_delete=models.CASCADE
    )

    class Meta:
        verbose_name = verbose_name_plural = '好友'
        unique_together = (('to_friend', 'from_friend'),)

    def __str__(self):
        return f'{self.from_friend!s}, {self.to_friend!s}'


class Invitation(BaseModel):
    """邀请模型"""
    name = models.CharField('朋友名字', max_length=50)
    email = models.EmailField('邮箱地址')
    code = models.CharField('邀请码', max_length=20)
    sender = models.ForeignKey(User, verbose_name='发送者', on_delete=models.CASCADE)

    class Meta:
        verbose_name = verbose_name_plural = '邀请'

    def __str__(self):
        return f'{self.sender!s}, {self.email}'

    def send(self):
        subject = '加入Django书签邀请'
        link = f'http://{settings.SITE_HOST}/accounts/friend/accept/{self.code}/'
        template = get_template('invitation_email.txt')
        context = {
            'name': self.name,
            'link': link,
            'sender': self.sender.username,
        }
        message = template.render(context)
        send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [self.email])
